package com.simon.jkxj.ui.home;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.simon.jkxj.R;
import android.app.Activity;

public class HomeFragment extends Fragment {

    private static final String TAG = "HomeFragment";
    
    private TabLayout tabLayout;
    private ViewPager2 viewPager;
    private FloatingActionButton postButton;
    private static final int REQUEST_CODE_PICK_IMAGE = 1001;
    private Uri selectedImageUri = null;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: 创建HomeFragment视图");
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated: 初始化HomeFragment视图组件");

        // 初始化视图
        tabLayout = view.findViewById(R.id.tab_bar_discovery_encyclopedia);
        viewPager = view.findViewById(R.id.home_content_container);
        postButton = view.findViewById(R.id.btn_post);

        // 设置ViewPager适配器
        setupViewPager();

        // 设置发布按钮点击事件
        postButton.setOnClickListener(v -> {
            // 弹出发布帖子Dialog
            Dialog dialog = new Dialog(requireContext());
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.dialog_post_publish);
            dialog.setCancelable(true);

            Button btnCancel = dialog.findViewById(R.id.btn_cancel_post);
            Button btnPublish = dialog.findViewById(R.id.btn_publish_post);
            Button btnSelectImage = dialog.findViewById(R.id.btn_select_image);
            EditText etTitle = dialog.findViewById(R.id.et_post_title);
            EditText etContent = dialog.findViewById(R.id.et_post_content);

            btnCancel.setOnClickListener(v1 -> dialog.dismiss());
            btnPublish.setOnClickListener(v2 -> {
                String title = etTitle.getText().toString().trim();
                String content = etContent.getText().toString().trim();
                if (title.isEmpty() || content.isEmpty()) {
                    Toast.makeText(requireContext(), "标题和内容不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(requireContext(), "发布成功", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });
            btnSelectImage.setOnClickListener(v3 -> {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
            });

            dialog.show();
        });
    }

    private void setupViewPager() {
        Log.d(TAG, "setupViewPager: 设置ViewPager适配器");
        
        // 设置必要的ViewPager2属性
        viewPager.setOffscreenPageLimit(2); // 预加载页面数量
        
        // 创建适配器
        HomeFragmentPagerAdapter pagerAdapter = new HomeFragmentPagerAdapter(requireActivity());
        viewPager.setAdapter(pagerAdapter);

        // 关联TabLayout和ViewPager
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> {
            // 设置标签页标题，覆盖XML中的设置
            if (position == 0) {
                tab.setText("发现");
            } else {
                tab.setText("百科");
            }
        }).attach();

        // 监听页面切换
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.d(TAG, "onPageSelected: 当前页面位置 " + position);
                // 根据页面显示或隐藏发布按钮
                if (position == 0) {
                    // 发现页面显示发布按钮
                    postButton.show();
                } else {
                    // 百科页面隐藏发布按钮
                    postButton.hide();
                }
            }
        });
        
        // 确保默认显示第一个页面
        viewPager.setCurrentItem(0, false);
    }
    
    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: HomeFragment已恢复");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            selectedImageUri = data.getData();
            // 这里只做前端演示，不显示图片
        }
    }

    /**
     * ViewPager适配器，用于管理发现和百科两个子Fragment
     */
    private static class HomeFragmentPagerAdapter extends FragmentStateAdapter {
        private static final String TAG = "PagerAdapter";

        public HomeFragmentPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            Log.d(TAG, "createFragment: 创建位置 " + position + " 的Fragment");
            // 根据位置创建对应的Fragment
            if (position == 0) {
                // 发现页面
                return new DiscoveryFragment();
            } else {
                // 百科页面
                return new EncyclopediaFragment();
            }
        }

        @Override
        public int getItemCount() {
            // 只有两个页面：发现和百科
            return 2;
        }
    }
} 